import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import debounce from 'lodash.debounce'
import { Button, Input, Popover, message, Icon, Form } from 'antd';
import ResizeTable from 'components/resize-table'
import strategyService from 'containers/budget-setting/budget-organization/budget-strategy/budget-strategy.service'
import BasicInfo from 'components/basic-info'
import 'styles/budget-setting/budget-organization/budget-strategy/budget-strategy-detail.scss'
import LanguageInput from 'components/template/language-input/language-input';

const Search = Input.Search;
const FormItem = Form.Item;

class BudgetStrategyDetail extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      infoList: [
        {type: 'input', id: 'controlStrategyCode', label: messages('budget-setting.key141'/*预算控制策略代码*/), isRequired: true, disabled: true},
        {type: 'switch', id: 'isEnabled', label: messages('common.column.status')/*状态*/}
      ],
      extraInfo: [
        {type: 'input', id: 'controlStrategyName', label: messages('budget-setting.key142'/*预算控制策略名称*/), isRequired: true}
      ],
      infoData: {},
      updateState: false,
      baseInfoLoading: false,
      columns: [
        {title: messages('common.sequence')/*序号*/, dataIndex: "detailSequence", key: "detailSequence", width: '7%'},
        {title: messages('budget-setting.key143'/*规则代码*/), dataIndex: "detailCode", key: "detailCode"},
        {title: messages('budget-setting.key36'/*控制策略*/), dataIndex: "controlMethod", key: "controlMethod",
          render: method => <span>{method.label}</span>},
        {title: messages('budget-setting.key144'/*控制规则名称*/), dataIndex: "detailName", key: "detailName",
          render: desc => <Popover placement="topLeft" content={desc}>{desc}</Popover>},
        {title: messages('budget-setting.key145'/*消息*/), dataIndex: "messageCode", key: "messageCode",
          render: (message, record) => (record.controlMethod.value === 'NO_MESSAGE' ? <span>-</span> :
            <Popover placement="topLeft" content={message ? JSON.parse(JSON.stringify(message)).label : '-'}>
              {message ? JSON.parse(JSON.stringify(message)).label : '-'}
            </Popover> )},
        {title: messages('budget-setting.key146'/*事件*/), dataIndex: "expWfEvent", key: "expWfEvent",
          render: event => <span>{event ? event : '-'}</span>}
      ],
      data: [],
      pagination: {
        total: 0
      },
      pageSize: 10,
      page: 0,
      keyWords: '',
      newBudgetStrategyDetail:  menuRoute.getRouteItem('new-budget-strategy-detail','key'),    //新建控制策略详情
      strategyControlDetail:  menuRoute.getRouteItem('strategy-control-detail','key'),    //策略明细
      budgetStrategyDetail:  menuRoute.getRouteItem('budget-strategy-detail','key'),    //预算控制策略详情
      budgetOrganizationDetail:  menuRoute.getRouteItem('budget-organization-detail','key'),    //预算组织详情
      i18n: {}
    };
    this.handleSearch = debounce(this.handleSearch, 250);
  }

  componentDidMount() {
    if(this.props.organization.id && this.props.params.strategyId){
      this.context.router.replace(this.state.budgetStrategyDetail.url.replace(':id', this.props.organization.id).replace(':strategyId', this.props.params.strategyId));
      this.getBasicInfo();
      this.getList();
    }
  }

  getBasicInfo() {
    strategyService.getStrategyInfo(this.props.params.strategyId).then(res => {
      if(res.status === 200) {
        this.setState({
          infoData: res.data,
          i18n: res.data.i18n || {},
          controlStrategyName: res.data.controlStrategyName
        });
      }
    })
  }

  getList() {
    const { page, pageSize, keyWords } = this.state;
    let strategyId = this.props.params.strategyId;
    this.setState({ loading: true });
    strategyService.getStrategyDetailList(page, pageSize, strategyId, this.props.params.id, keyWords)
      .then(res => {
        if (res.status === 200) {
          this.setState({
            data: res.data,
            pagination: {
              total: Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0,
              onChange: this.onChangePager,
              current: this.state.page + 1
            }
          });
        }
      })
      .catch(err => {
        message.error(err.response.data.message);
      })
      .finally(() => {
        this.setState({ loading: false });
      });
  }

  //分页点击
  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, ()=>{
        this.getList();
      })
  };

  handleNew = () => {
    this.context.router.push(this.state.newBudgetStrategyDetail.url.replace(':id', this.props.params.id).replace(':strategyId', this.props.params.strategyId));
  };

  handleRowClick = (record) => {
    this.context.router.push(this.state.strategyControlDetail.url.replace(':id', this.props.params.id).replace(':strategyId', this.props.params.strategyId).replace(':strategyControlId', record.id));
  };

  handleSearch= (value) => {
    this.setState({
      page: 0,
      keyWords: value,
      pagination: {
        current: 1
      }
    }, () => {
      this.getList();
    })
  };

  //更新基本信息
  handleUpdate = (params) => {
    const { i18n, controlStrategyName } = this.state;
    params.id = this.props.params.strategyId;
    params.versionNumber = this.state.infoData.versionNumber;
    if (!controlStrategyName) return;
    this.setState({ baseInfoLoading: true }, () => {
      strategyService.updateStrategy({ ...params, ...{ i18n, controlStrategyName } })
        .then((res) => {
          if (res.status === 200) {
            message.success(messages('common.save.success', { name: '' })/*保存成功*/);
            this.getBasicInfo();
          }
        })
        .catch((e) => {
          message.error(`${messages('common.save.filed')/*保存失败*/}, ${e.response.data.message}`);
        })
        .finally(() => {
          this.setState({ updateState: true, baseInfoLoading: false }, () => {
            this.setState({ updateState: false });
          });
        });
    });
  };

  //返回到预算组织详情页
  handleBack = () => {
    this.context.router.push(this.state.budgetOrganizationDetail.url.replace(':id', this.props.params.id) + '?tab=STRATEGY');
  };

  handleI18n = (name, value) => {
    let { i18n, controlStrategyName } = this.state;
      i18n.controlStrategyName = value;
    controlStrategyName = name;
    this.setState({ controlStrategyName, i18n });
  };

  renderExtraFields = () => {
    const { i18n, extraInfo } = this.state;
    const { form: { getFieldDecorator } } = this.props;
    return extraInfo.map(item =>
      <FormItem label={item.label}>
        {getFieldDecorator(item.id, {
          initialValue: this.state[item.id],
          rules: [{
            required: item.isRequired,
            message: messages('common.can.not.be.empty', { name: item.label }),  //name 不可为空
          }]
        })(
          <LanguageInput
            key={item.id}
            isEdit={true}
            i18nName={i18n[item.id] || null}
            nameChange={this.handleI18n}
            placeholder={messages('common.please.enter')/* 请输入 */}
            mainLanguageIsRequired={!!item.isRequired}/>
        )}
      </FormItem>
    );
  };

  render(){
    const { infoList, infoData, columns, data, loading, pagination, updateState, baseInfoLoading, extraInfo } = this.state;

    return (
      <div className="budget-strategy-detail">
        <BasicInfo
          infoList={infoList}
          infoData={infoData}
          extraFields={this.renderExtraFields()}
          extraFieldsIndex={1}
          extraInfo={extraInfo}
          updateHandle={this.handleUpdate}
          updateState={updateState}
          loading={baseInfoLoading}/>
        <div className="table-header">
          <div className="table-header-title">
            <h5>{messages('budget-setting.key147'/*策略明细*/)}</h5>
            {messages('common.total',{total:`${pagination.total || 0}`})/*共搜索到 {total} 条数据*/}
          </div>
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleNew}>{messages('common.create')/*新建*/}</Button>
            <Search className="input-search"
                    placeholder={messages('budget-setting.key148'/*请输入策略明细名称/代码*/)}
                    onChange={(e) => this.handleSearch(e.target.value)} />
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          rowKey={record => record.id}
          loading={loading}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          bordered
          size="middle"
        />
        <a style={{fontSize:'14px',paddingBottom:'20px'}} onClick={this.handleBack}>
          <Icon type="rollback" style={{marginRight:'5px'}}/>
          {messages('common.back')/*返回*/}
        </a>
      </div>
    )
    }
}

BudgetStrategyDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
  }
}

const WrappedBudgetStrategyDetail = Form.create()(BudgetStrategyDetail);

export default connect(mapStateToProps)(WrappedBudgetStrategyDetail);

